package com.juzipi.demo.handler;

import com.juzipi.demo.constant.ResultCode;
import com.juzipi.demo.tools.json.ResultTool;
import com.juzipi.demo.utils.json.JsonAuthentication;
import com.juzipi.demo.utils.json.Result;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义登陆失败
 */
@Component
public class MyAuthenticationFailureHandler extends JsonAuthentication implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        Result result = null;
        //账号过期
        if (e instanceof AccountExpiredException){
            result = ResultTool.failCustomize(ResultCode.USER_ACCOUNT_EXPIRED,null);
        }
        //密码错误
        if (e instanceof BadCredentialsException){
            result = ResultTool.failCustomize(ResultCode.USER_PASSWORD_ERROR,null);
        }
        //账号不存在
        if (e instanceof InternalAuthenticationServiceException){
            result = ResultTool.failCustomize(ResultCode.USER_ACCOUNT_NOT_EXIST,null);
        }
        //账号未启用
        if (e instanceof DisabledException){
            result = ResultTool.failCustomize(ResultCode.USER_ACCOUNT_DISABLE,null);
        }
        //账号已锁定
        if (e instanceof LockedException){
            result = ResultTool.failCustomize(ResultCode.USER_ACCOUNT_LOCKED,null);
        }
        this.WriteJson(httpServletRequest,httpServletResponse,result);
    }

}
